<template>
  <div v-if="visible" class="modal-overlay" @click="handleClose">
    <div class="modal-content" @click.stop>
      <div class="modal-header">
        <h3>{{ isEdit ? '编辑账户' : '添加账户' }}</h3>
        <button class="close-button" @click="handleClose">×</button>
      </div>

      <form @submit.prevent="handleSubmit" class="account-form">
        <div class="form-grid">
          <!-- 账户名称 -->
          <div class="form-group full-width">
            <label for="name">账户名称 *</label>
            <input
              id="name"
              v-model="formData.name"
              type="text"
              required
              placeholder="请输入账户名称"
              :disabled="!!isEdit"
              :readonly="!!isEdit"
            />
            <small v-if="isEdit" class="field-hint">账户名称创建后不可修改</small>
          </div>

          <!-- 账户类型 -->
          <div class="form-group">
            <label for="account_type">账户类型 *</label>
            <select
              id="account_type"
              v-model="formData.account_type"
              required
              placeholder="请选择账户类型"
            >
              <option value="cash">现金</option>
              <option value="bank">银行卡</option>
              <option value="credit">信用卡</option>
              <option value="alipay">支付宝</option>
              <option value="wechat">微信支付</option>
              <option value="other">其他</option>
            </select>
          </div>

          <!-- 初始余额 -->
          <div class="form-group">
            <label for="initial_balance">初始余额</label>
            <input
              id="initial_balance"
              v-model="formData.initial_balance"
              type="number"
              step="0.01"
              placeholder="0.00"
            />
          </div>

          <!-- 图标 -->
          <div class="form-group">
            <label for="icon">图标</label>
            <input
              id="icon"
              v-model="formData.icon"
              type="text"
              placeholder="例如：💳、🏦、💰"
            />
          </div>

          <!-- 颜色 -->
          <div class="form-group">
            <label for="color">颜色</label>
            <div class="color-input-group">
              <input
                id="color"
                v-model="formData.color"
                type="color"
                class="color-picker"
              />
              <input
                v-model="formData.color"
                type="text"
                class="color-text"
                placeholder="#007aff"
              />
            </div>
          </div>

          <!-- 描述 -->
          <div class="form-group full-width">
            <label for="description">描述</label>
            <textarea
              id="description"
              v-model="formData.description"
              rows="3"
              placeholder="请输入账户描述..."
            ></textarea>
          </div>
        </div>

        <!-- 预览 -->
        <div class="preview-section">
          <h4>预览</h4>
          <div class="account-preview">
            <div
              class="account-icon-preview"
              :style="{ backgroundColor: formData.color || '#007aff' }"
            >
              <span v-if="formData.icon">{{ formData.icon }}</span>
              <svg
                v-else
                width="24"
                height="24"
                viewBox="0 0 24 24"
                fill="none"
                stroke="currentColor"
                stroke-width="2"
              >
                <path
                  d="M12 2v20M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6"
                />
              </svg>
            </div>
            <div class="account-info-preview">
              <div class="account-name-preview">
                {{ formData.name || "账户名称" }}
              </div>
              <div class="account-type-preview">
                {{ getAccountTypeLabel(formData.account_type) }}
              </div>
              <div class="account-balance-preview">
                ¥{{
                  formatAmount(parseFloat(formData.initial_balance || "0") || 0)
                }}
              </div>
            </div>
          </div>
        </div>

        <div class="form-actions">
          <button type="button" class="btn-cancel" @click="handleClose">
            取消
          </button>
          <button type="submit" class="btn-primary" :disabled="loading">
            {{ loading ? (isEdit ? "更新中..." : "创建中...") : (isEdit ? "更新账户" : "创建账户") }}
          </button>
        </div>
      </form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, watch, computed } from "vue";
import { useAccountingStore } from "@/stores/accounting";
import type { AccountCreate, AccountType, AccountResponse } from "@/types/accounting";

interface Props {
  visible: boolean;
  editData?: AccountResponse | null;
}

interface Emits {
  (e: "update:visible", visible: boolean): void;
  (e: "close"): void;
  (e: "success"): void;
}

const props = defineProps<Props>();
const emit = defineEmits<Emits>();

const accountingStore = useAccountingStore();

// 编辑模式状态
const isEdit = computed(() => props.editData && props.editData.id);

// 表单数据
const formData = reactive<AccountCreate>({
  name: "",
  account_type: "cash" as AccountType,
  initial_balance: "0",
  icon: null,
  color: "#007aff",
  description: null,
});

// 加载状态
const loading = ref(false);

// 监听visible变化，重置表单
watch(
  () => props.visible,
  (newVisible) => {
    if (newVisible) {
      resetForm();
    }
  },
);

// 重置表单
function resetForm() {
  if (props.editData) {
    // 编辑模式：填充现有数据
    formData.name = props.editData.name;
    formData.account_type = props.editData.account_type;
    formData.initial_balance = props.editData.balance;
    formData.icon = props.editData.icon;
    formData.color = props.editData.color || "#007aff";
    formData.description = props.editData.description;
  } else {
    // 添加模式：清空表单
    formData.name = "";
    formData.account_type = "cash" as AccountType;
    formData.initial_balance = "0";
    formData.icon = null;
    formData.color = "#007aff";
    formData.description = null;
  }
}

// 获取账户类型标签
function getAccountTypeLabel(type: AccountType): string {
  const typeLabels: Record<AccountType, string> = {
    cash: "现金",
    bank: "银行卡",
    credit_card: "信用卡",
    alipay: "支付宝",
    wechat: "微信支付",
    other: "其他",
  };
  return typeLabels[type] || type;
}

// 格式化金额
function formatAmount(amount: number): string {
  return amount.toFixed(2);
}

// 处理关闭
function handleClose() {
  emit("update:visible", false);
  emit("close");
}

// 处理提交
async function handleSubmit() {
  if (!formData.name || !formData.account_type) {
    alert("请填写所有必填字段");
    return;
  }

  try {
    loading.value = true;

    // 验证初始余额
    const initialBalance = parseFloat(formData.initial_balance || "0");
    if (isNaN(initialBalance) || initialBalance < 0) {
      alert("请输入有效的初始余额");
      return;
    }

    // 准备提交数据
    const submitData: AccountCreate = {
      name: formData.name.trim(),
      account_type: formData.account_type,
      initial_balance: formData.initial_balance,
      icon: formData.icon?.trim() || null,
      color: formData.color || "#007aff",
      description: formData.description?.trim() || null,
    };

    if (isEdit.value && props.editData) {
      // 编辑模式：更新账户
      await accountingStore.updateAccount(props.editData.id, submitData);
    } else {
      // 添加模式：创建账户
      await accountingStore.createAccount(submitData);
    }

    // 成功后关闭模态框
    emit("success");
    emit("close");
  } catch (error) {
    console.error(isEdit.value ? "更新账户失败:" : "创建账户失败:", error);
    alert(isEdit.value ? "更新账户失败，请重试" : "创建账户失败，请重试");
  } finally {
    loading.value = false;
  }
}
</script>

<style lang="scss" scoped>
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 2000;
  backdrop-filter: blur(5px);
}

.modal-content {
  background: var(--el-bg-color);
  border-radius: var(--el-border-radius-base);
  box-shadow: var(--el-box-shadow-light);
  width: 90%;
  max-width: 500px;
  max-height: 90vh;
  overflow-y: auto;
  border: 1px solid var(--el-border-color);
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid var(--el-border-color);

  h3 {
    margin: 0;
    font-size: 18px;
    font-weight: 600;
    color: var(--el-text-color-primary);
    font-family:
      -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
  }
}

.close-button {
  background: none;
  border: none;
  font-size: 20px;
  color: var(--el-text-color-secondary);
  cursor: pointer;
  padding: 4px;
  border-radius: var(--el-border-radius-small);
  transition: all 0.3s ease;

  &:hover {
    background: rgba(0, 0, 0, 0.1);
    color: var(--el-text-color-primary);
  }
}

.account-form {
  padding: 20px;
}

.form-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 16px;

  .full-width {
    grid-column: 1 / -1;
  }
}

.form-group {
  display: flex;
  flex-direction: column;
  gap: 8px;

  label {
    font-size: 14px;
    font-weight: 500;
    color: var(--el-text-color-primary);
    font-family:
      -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
  }

  .field-hint {
    font-size: 12px;
    color: var(--el-color-warning);
    margin-top: 4px;
    font-style: italic;
  }
}

input[type="text"],
input[type="number"],
input[type="color"],
select,
textarea {
  background: var(--el-bg-color);
  border: 1px solid var(--el-border-color);
  border-radius: var(--el-border-radius-small);
  font-size: 14px;
  padding: 8px 16px;
  outline: none;
  transition: all 0.3s ease;

  &:focus {
    border-color: var(--el-color-primary);
    box-shadow: 0 0 0 3px rgba(var(--el-color-primary-rgb), 0.1);
  }
}

textarea {
  resize: vertical;
  min-height: 80px;
}

.color-input-group {
  display: flex;
  gap: 8px;
  align-items: center;

  .color-picker {
    width: 50px;
    height: 36px;
    border-radius: var(--el-border-radius-small);
    border: 1px solid var(--el-border-color);
    cursor: pointer;

    &::-webkit-color-swatch-wrapper {
      padding: 0;
    }

    &::-webkit-color-swatch {
      border: none;
      border-radius: var(--el-border-radius-small);
    }
  }

  .color-text {
    flex: 1;
  }
}

.preview-section {
  margin: 24px 0;
  padding: 16px;
  background: var(--el-bg-color-overlay);
  border-radius: var(--el-border-radius-small);

  h4 {
    margin: 0 0 8px 0;
    font-size: 14px;
    font-weight: 500;
    color: var(--el-text-color-primary);
    font-family:
      -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
  }
}

.account-preview {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 8px;
  background: var(--el-bg-color);
  border-radius: var(--el-border-radius-small);
  border: 1px solid var(--el-border-color);
}

.account-icon-preview {
  width: 40px;
  height: 40px;
  border-radius: var(--el-border-radius-small);
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  flex-shrink: 0;

  svg {
    width: 20px;
    height: 20px;
    color: white;
  }
}

.account-info-preview {
  flex: 1;
}

.account-name-preview {
  font-size: 16px;
  font-weight: 500;
  color: var(--el-text-color-primary);
  margin: 0 0 4px 0;
  font-family:
    -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
}

.account-type-preview {
  font-size: 14px;
  color: var(--el-text-color-secondary);
  margin: 0 0 4px 0;
}

.account-balance-preview {
  font-size: 18px;
  font-weight: 600;
  color: var(--el-text-color-primary);
  margin: 0;
  font-family:
    -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
}

.form-actions {
  display: flex;
  justify-content: space-between;
  gap: 16px;
  margin-top: 24px;

  button {
    flex: 1;
    padding: 12px 20px;
    border: none;
    border-radius: var(--el-border-radius-small);
    font-size: 14px;
    font-weight: 500;
    cursor: pointer;
    transition: all 0.3s ease;
    font-family:
      -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;

    &:disabled {
      opacity: 0.5;
      cursor: not-allowed;
    }
  }
}

.btn-cancel {
  background: var(--el-bg-color);
  color: var(--el-text-color-secondary);
  border: 1px solid var(--el-border-color);

  &:hover:not(:disabled) {
    background: var(--el-bg-color-overlay);
    color: var(--el-text-color-primary);
  }
}

.btn-primary {
  background: var(--el-color-primary);
  color: white;

  &:hover:not(:disabled) {
    background: var(--el-color-primary-light-3);
    transform: translateY(-1px);
  }
}

@media (max-width: 768px) {
  .modal-content {
    width: 95%;
    max-width: none;
  }

  .form-grid {
    grid-template-columns: 1fr;
  }

  .color-input-group {
    flex-direction: column;
    align-items: stretch;

    .color-picker {
      width: 100%;
    }
  }

  .form-actions {
    flex-direction: column;
  }
}
</style>
